package cn.pconline.autoclub.web.admin;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.gelivable.auth.entity.GeliSession;
import org.gelivable.auth.entity.GeliUser;
import org.gelivable.webmvc.JSONBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.pconline.autoclub.entity.Gift;
import cn.pconline.autoclub.entity.GiftConversion;
import cn.pconline.autoclub.entity.UpgradeGift;
import cn.pconline.autoclub.entity.UpgradeGiftReward;
import cn.pconline.autoclub.entity.UpgradeRule;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.MessageService;
import cn.pconline.autoclub.service.UpgradeGiftRewardService;
import cn.pconline.autoclub.service.UpgradeGiftService;
import cn.pconline.autoclub.service.UpgradeRuleService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.WebUtils;

/**
 * Controller-升级礼品
 * @author zhoutianhuai
 */
@Controller
@RequestMapping(value = "/admin")
public class AdminUpgradeGiftController {

    @Autowired
    private UpgradeGiftService upgradeGiftService;
    @Autowired
    private UpgradeGiftRewardService upgradeGiftRewardService;
    @Autowired
    private UpgradeRuleService upgradeRuleService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private UserService userService;
    @Autowired
    private ClubService clubService;
    private static final Logger log = LoggerFactory.getLogger(AdminUpgradeGiftController.class);

    /**
     * 创建升级礼品
     *
     * @param request
     * @param resp
     */
    @RequestMapping(value = "/upgradeGift/create", method = RequestMethod.POST)
    public void createGift(HttpServletRequest request, HttpServletResponse resp) {
        String name = WebUtils.param(request, "name", "");
        int total = WebUtils.paramInt(request, "total", 0, 0, Integer.MAX_VALUE);
        int valuePoint = WebUtils.paramInt(request, "valuePoint", 0, 0, Integer.MAX_VALUE);
        String url = WebUtils.param(request, "url", "");
        int status = WebUtils.paramInt(request, "status", Gift.STATUS_DOWN);
        int seq = WebUtils.paramInt(request, "seq", 0);
        int isRequired = WebUtils.paramInt(request, "isRequired", 0);
        String link = WebUtils.param(request, "link", "");
        if (!checkGiftInfo(name, valuePoint, total, seq, url, resp)) {
            return;
        }
        GeliUser geliUser = GeliSession.getCurrentUser();
        if (geliUser != null) {
            UpgradeGift gift = new UpgradeGift();
            gift.setName(name);
            gift.setGiftUrl(url);
            gift.setValuePoint(valuePoint);
            gift.setTotal(total);
            gift.setCurNum(total);
            gift.setSeq(seq);
            gift.setCreateBy(geliUser.getUserId());
            gift.setStatus(status);
            gift.setLink(link);
            gift.setIsRequired(isRequired);
            long id = upgradeGiftService.createUpgradeGift(gift);
            if (id > 0) {
                successMsg(resp, "list-upgradegift", "创建成功", "closeCurrent");
            } else {
                errorMsg(resp, "创建失败");
            }
        } else {
            errorMsg(resp, "请登陆后操作");
        }
    }
    
    /**
     * 创建升级奖励规则
     *
     * @param request
     * @param resp
     */
    @RequestMapping(value = "/upgradeRule/create", method = RequestMethod.POST)
    public void createUpgradeRule(HttpServletRequest request, HttpServletResponse resp) {
        String ruleDesc = WebUtils.param(request, "ruleDesc", "");
        int levelId = WebUtils.paramInt(request, "levelId", 0);
        int valuePoint = WebUtils.paramInt(request, "valuePoint", 0, 0, Integer.MAX_VALUE);
  /*      if("".equals(ruleDesc)){
        	String[] ruleDescArrary = ruleDesc.split("<br>");
        	String rule = "";
        	for(String r : ruleDescArrary){
        		rule +="<p>"+r+"</p>";
        	}
        	ruleDesc = rule;
        }*/
        
        GeliUser geliUser = GeliSession.getCurrentUser();
        if (geliUser != null) {
            UpgradeRule upgradeRule = new UpgradeRule();
            upgradeRule.setValuePoint(valuePoint);
            upgradeRule.setCreateBy(geliUser.getUserId());
            upgradeRule.setRuleDesc(ruleDesc);
            upgradeRule.setLevelId(levelId);
            long id = upgradeRuleService.createUpgradeRule(upgradeRule);
            if (id > 0) {
                successMsg(resp, "list-upgraderule", "创建成功", "closeCurrent");
            } else {
                errorMsg(resp, "创建失败");
            }
        } else {
            errorMsg(resp, "请登陆后操作");
        }
    }

    /**
     * 升级礼品详情
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/upgradeGift/giftDetail.do")
    public String giftDetail(HttpServletRequest req, HttpServletResponse resp) {
        long giftId = WebUtils.paramLong(req, "giftId", 0);
        UpgradeGift gift = upgradeGiftService.findUpgradeGift(giftId);
        req.setAttribute("gift", gift);
        return "admin/upgradeGift/update";
    }
 
    /**
     * 升级规则详情
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/upgradeRule/ruleDetail.do")
    public String ruleDetail(HttpServletRequest req, HttpServletResponse resp) {
        long ruleId = WebUtils.paramLong(req, "ruleId", 0);
        UpgradeRule rule = upgradeRuleService.findUpgradeRule(ruleId);
        req.setAttribute("rule", rule);
        return "admin/upgradeRule/update";
    }


    /**
     * 修改礼品信息
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/upgradeGift/update")
    public void updateGift(HttpServletRequest req, HttpServletResponse resp) {
        long giftId = WebUtils.paramLong(req, "giftId", 0);
        String name = WebUtils.param(req, "name", "");
        int total = WebUtils.paramInt(req, "total", 0);
        int curNum = WebUtils.paramInt(req, "curNum", 0);
        int valuePoint = WebUtils.paramInt(req, "valuePoint", 0);
        String url = WebUtils.param(req, "url", "");
        int status = WebUtils.paramInt(req, "status", Gift.STATUS_DOWN);
        int seq = WebUtils.paramInt(req, "seq", 0);
        int isRequired = WebUtils.paramInt(req, "isRequired", 0);
        String link = WebUtils.param(req, "link", "");
        if (!checkGiftInfo(name, valuePoint, total, seq, url, resp)) {
            return;
        }
        UpgradeGift gift = upgradeGiftService.findUpgradeGift(giftId);
        if (gift == null) {
            errorMsg(resp, "giftId有误!");
            return;
        }
        gift.setName(name);
        gift.setGiftUrl(url);
        gift.setTotal(total);
        gift.setCurNum(curNum);
        gift.setStatus(status);
        gift.setValuePoint(valuePoint);
        gift.setSeq(seq);
        gift.setLink(link);
        gift.setIsRequired(isRequired);
        long count = upgradeGiftService.updateUpgradeGift(gift);
        if (count > 0) {
            successMsg(resp, "list-upgradegift", "修改成功", "closeCurrent");
        } else {
            errorMsg(resp, "修改失败");
        }
    }
    
    /**
     * 升星规则修改
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/upgradeRule/update")
    public void updateUpgradeRule(HttpServletRequest request, HttpServletResponse resp) {
    	  String ruleDesc = WebUtils.param(request, "ruleDesc", "");
    	  int levelId = WebUtils.paramInt(request, "levelId", 0);
          long ruleId = WebUtils.paramLong(request, "ruleId", 0);
          int valuePoint = WebUtils.paramInt(request, "valuePoint", 0, 0, Integer.MAX_VALUE);
/*          if("".equals(ruleDesc)){
          	String[] ruleDescArrary = ruleDesc.split("<br>");
          	String rule = "";
          	for(String r : ruleDescArrary){
          		rule +="<p>"+r+"</p>";
          	}
          	ruleDesc = rule;
          }*/
          UpgradeRule upgradeRule = upgradeRuleService.findUpgradeRule(ruleId);
          if (upgradeRule == null) {
              errorMsg(resp, "ruleId有误!");
              return;
          }
          GeliUser geliUser = GeliSession.getCurrentUser();
          if (geliUser != null) {
              upgradeRule.setValuePoint(valuePoint);
              upgradeRule.setRuleDesc(ruleDesc);
              upgradeRule.setLevelId(levelId);
              long id = upgradeRuleService.updateUpgradeRule(upgradeRule);
              if (id > 0) {
                  successMsg(resp, "list-upgraderule", "修改成功", "closeCurrent");
              } else {
                  errorMsg(resp, "修改失败");
              }
          } else {
              errorMsg(resp, "请登陆后操作");
          }
    }
    
    /**
     * 修改礼品状态
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/upgradeGift/editStatus", method = RequestMethod.POST)
    public void editStatus(HttpServletRequest req, HttpServletResponse resp) {
        int status = WebUtils.paramInt(req, "status", UpgradeGift.STATUS_DOWN);
        long giftId = WebUtils.paramLong(req, "giftId", 0);
        UpgradeGift gift = upgradeGiftService.findUpgradeGift(giftId);
        if (gift == null) {
            errorMsg(resp, "giftId有误!");
            return;
        }
        gift.setStatus(status);
        long count = upgradeGiftService.updateUpgradeGift(gift);
        if (count > 0) {
            successMsg(resp, "list-upgradegift", "操作成功", null);
        } else {
            errorMsg(resp, "修改失败");
        }
    }
    /**
     * 修改奖励状态
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/upgradeGift/editRewardStatus", method = RequestMethod.POST)
    public void editRewardStatus(HttpServletRequest req, HttpServletResponse resp) {
        int status = WebUtils.paramInt(req, "status", UpgradeGiftReward.STATUS_NOSEND);
        long rewardId = WebUtils.paramLong(req, "rewardId", 0);
        UpgradeGiftReward reward = upgradeGiftRewardService.findUpgradeGiftReward(rewardId);
        if (reward == null) {
            errorMsg(resp, "rewardId有误!");
            return;
        }
        reward.setStatus(status);
        long count = upgradeGiftRewardService.updateUpgradeGiftReward(reward);
        if (count > 0) {
            successMsg(resp, "list-upgradegiftreward", "操作成功", null);
        } else {
            errorMsg(resp, "修改失败");
        }
    }
    
    /**
     * 修改规则状态
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/upgradeRule/editStatus", method = RequestMethod.POST)
    public void editRuleStatus(HttpServletRequest req, HttpServletResponse resp) {
        int status = WebUtils.paramInt(req, "status", UpgradeGift.STATUS_DOWN);
        long ruleId = WebUtils.paramLong(req, "ruleId", 0);
        UpgradeRule rule = upgradeRuleService.findUpgradeRule(ruleId);
        if (rule == null) {
            errorMsg(resp, "ruleId有误!");
            return;
        }
        rule.setStatus(status);
        long count = upgradeRuleService.updateUpgradeRule(rule);
        if (count > 0) {
            successMsg(resp, "list-upgraderule", "操作成功", null);
        } else {
            errorMsg(resp, "修改失败");
        }
    }
    /**
     * 奖励记录导出
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/upgradeGift/exportUpgradeReward.do", produces = {"application/octet-stream"})
    public void exportUpgradeReward(HttpServletRequest req, HttpServletResponse resp) {
    	 long userId = WebUtils.paramLong(req, "userId", 0);
         long giftId = WebUtils.paramLong(req, "giftId", 0);
         long clubId = WebUtils.paramLong(req, "clubId", 0);
         String truename = WebUtils.param(req, "truename", "");
         String clubName = WebUtils.param( req, "clubname", "");
         int status = WebUtils.paramInt(req, "status", GiftConversion.STATUS_NOSELECT);
         String beginDate = WebUtils.param(req, "beginDate", "");
         String endDate = WebUtils.param(req, "endDate", "");
         int pageNo = WebUtils.paramInt(req, "pageNum", 1);
         int pageSize = WebUtils.paramInt(req, "pageSize", 20);
         Pager<UpgradeGiftReward> pager = upgradeGiftRewardService.pageUpgradeGiftRewardWithGift(userId, clubId, giftId, truename,clubName, status, beginDate, endDate, pageNo, pageSize);
        
         //导出excel
         String[] cellString = new String[]{"ID","所属车友会", "用户昵称", "真实姓名", "手机号码", "详细地址","邮编", "奖励礼品名称", "兑换数量", "申请时间", "处理状态"};
         HSSFWorkbook work = new HSSFWorkbook();
         HSSFSheet sheet = work.createSheet("奖励记录列表");
         HSSFRow row = sheet.createRow(0);
         for (int i = 0; i < cellString.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(cellString[i]);
         }
         
        /**
         * 根据分页数据生成excel文件
         */
        for (int curPage = pageNo; curPage <= pager.getPageCount(); curPage++) {
            // 数据一页一页加载
            if (curPage != pageNo) {
              pager = upgradeGiftRewardService.pageUpgradeGiftRewardWithGift(userId, clubId, giftId, truename,clubName, status, beginDate, endDate, curPage, pageSize);
            }   
	        for (int i = 0; i < pager.getResultList().size(); i++) {
	        	    UpgradeGiftReward g = pager.getResultList().get(i);
	        	    HSSFRow rowData = sheet.createRow(((curPage - 1) * pageSize) + i + 1);
	                rowData.createCell(0).setCellValue(g.getRewardId());
	                rowData.createCell(1).setCellValue( g.getClub().getName() );
	                rowData.createCell(2).setCellValue(g.getUser().getNickname());
	                rowData.createCell(3).setCellValue(g.getTrueName());
	                rowData.createCell(4).setCellValue(g.getPhone());
	                rowData.createCell(5).setCellValue(g.getAddress());
	                rowData.createCell(6).setCellValue(g.getPostcode());
	                rowData.createCell(7).setCellValue(g.getUpgradeGift().getName());
	                rowData.createCell(8).setCellValue(g.getNum());
	                rowData.createCell(9).setCellValue(DateUtils.formatDetail(g.getCreateAt()));
	                rowData.createCell(10).setCellValue(g.getStatus() == 1 ? "已发货" : g.getStatus()==0 ? "待发货" : "驳回" );
	            }
        }

        try {
            //设置返回数据类型
            resp.setContentType("application/vnd.ms-excel;charset=GBK");
            //设置返回的文件名
            resp.setHeader("Content-Disposition", 
            		"attachment;Filename=RewardList.xls");
            OutputStream out = resp.getOutputStream();
            work.write(out);
            out.flush();
            out.close();
        } catch (IOException ex) {
            log.error("Export rewards fail!", ex);
        }
    }

    /**
     * 页面跳转
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/upgradeGift/goToCreate", method = RequestMethod.GET)
    public String goToCreate(HttpServletRequest req, HttpServletResponse resp) {
        return "admin/upgradeGift/create";
    }
    

    /**
     * 页面跳转
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/upgradeRule/goToCreate", method = RequestMethod.GET)
    public String goToRuleCreate(HttpServletRequest req, HttpServletResponse resp) {
        return "admin/upgradeRule/create";
    }
    /**
     * 查询奖励记录
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/upgradeGift/listReward.do")
    public String listUpgradeReward(HttpServletRequest req, HttpServletResponse resp) {
        long userId = WebUtils.paramLong(req, "userId", 0);
        long giftId = WebUtils.paramLong(req, "giftId", 0);
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        String truename = WebUtils.param(req, "truename", "");
        String clubName = WebUtils.param( req, "clubname", "");
        int status = WebUtils.paramInt(req, "status", GiftConversion.STATUS_NOSELECT);
        String beginDate = WebUtils.param(req, "beginDate", "");
        String endDate = WebUtils.param(req, "endDate", "");
        int pageNo = WebUtils.paramInt(req, "pageNum", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", 20);
        Pager<UpgradeGiftReward> pager = upgradeGiftRewardService.pageUpgradeGiftRewardWithGift(userId, clubId, giftId, truename,clubName, status, beginDate, endDate, pageNo, pageSize);
        req.setAttribute("pager", pager);
        req.setAttribute("truename", truename);
        req.setAttribute("clubname", clubName);
        req.setAttribute("status", status);
        req.setAttribute("beginDate", beginDate);
        req.setAttribute("endDate", endDate);
        return "admin/upgradeGift/listReward";
    }
    

    /**
     * 礼品列表
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/upgradeGift/list.do")
    public String list(HttpServletRequest req, HttpServletResponse resp) {
        int pageNo = WebUtils.paramInt(req, "pageNum", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", 20);
        Pager<UpgradeGift> pager = upgradeGiftService.pageUpgradeGiftForAdmin(pageNo, pageSize);
        req.setAttribute("pager", pager);
        return "admin/upgradeGift/list";
    }
    
    /**
     * 规则列表
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/upgradeRule/list.do")
    public String listUpgradeRule(HttpServletRequest req, HttpServletResponse resp) {
        int pageNo = WebUtils.paramInt(req, "pageNum", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", 20);
        Pager<UpgradeRule> pager = upgradeRuleService.pageUpgradeRule(pageNo, pageSize);
        req.setAttribute("pager", pager);
        return "admin/upgradeRule/list";
    }

    /**
     * 成功返回消息
     *
     * @param resp
     * @param navTabId
     * @param msg
     * @param callbackType closeCurrent 关闭当前tab forward reload
     */
    private void successMsg(HttpServletResponse resp, String navTabId, String msg, String callbackType) {
        try {
            resp.setCharacterEncoding("UTF-8");
            PrintWriter out = resp.getWriter();
            out.println(new JSONBuilder().put("statusCode", 200).put("message", msg).put("navTabId", navTabId).put("callbackType", callbackType).toString());
        } catch (IOException ex) {
            log.error("set successMsg fail!", ex);
        }
    }

    private void errorMsg(HttpServletResponse resp, String msg) {
        try {
            resp.setCharacterEncoding("UTF-8");
            PrintWriter out = resp.getWriter();
            out.println(new JSONBuilder().put("statusCode", 300).put("message", msg).toString());
        } catch (IOException ex) {
            log.error("set errorMsg fail!", ex);
        }
    }

    private boolean checkGiftInfo(String name, int valuePoint, int total, int seq, String url, HttpServletResponse resp) {
        if (StringUtils.isBlank(name) || StringUtils.length(name) > 12) {
            errorMsg(resp, "请输入正确的礼品名称");
            return false;
        }
        if (valuePoint <= 0) {
            errorMsg(resp, "所需价值点必须大于0");
            return false;
        }
        if (total <= 0) {
            errorMsg(resp, "商品数量必须大于0");
            return false;
        }
        if (seq <= 0) {
            errorMsg(resp, "序号必须大于0");
            return false;
        }
        if (StringUtils.isBlank(url)) {
            errorMsg(resp, "礼品图片不能为空");
            return false;
        }
        return true;
    }

}
